<?php

namespace app\model\agency;

use app\base\BaseModel;
use app\libs\Util;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 模型-agency_title
 * Class agency_title
 * @package app\model
 */
class AgencyModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'agency';

    /**
     * 还原数据
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function backData($id)
    {
        $self_obj = self::onlyTrashed()->find($id);
        $this->setRedis($self_obj->toArray());
        if ($self_obj['status'] == 1) {
            $this->redis->zAdd($this->redis_key . ':rank', $self_obj['rank'], $self_obj['id']);
        }
        return $self_obj->restore();
    }


    /**
     * 获取数据是否存在
     * @param $phone
     * @return array|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_user_exist($phone)
    {
        $data = $this->where('agency_login_username', $phone)->field("id")->find();
        return $data;
    }


    /**
     * 范围查询-status
     * @param $query
     * @param $status
     */
    public function scopeStatus($query, $status)
    {
        if ($status != null) {
            $query->where('status', '=', $status);
        }
    }

    /**
     * 范围查询-keyword
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('agency_title', '%' . trim($keyword) . '%');
        }
    }

    /**
     * 获取分页列表
     * @param $status
     * @param $jump_type
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageData($status, $keyword, $current_page, $list_rows, $field = 'a.*,count(b.order_id) as order_num,sum(b.agency_money) as cons_all')
    {
        $dataList = $this
            ->alias('a')
            ->leftJoin('t_order_item b', 'b.agency_id=a.id')
            ->field($field)
            ->status($status)
            ->group('a.id')
            ->keyword($keyword)
            ->order('create_time', 'desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false)->each(function ($item, $value) {
                $item['earnings_num'] = Db::name('agency_earnings')->where('agency_id', $item['id'])->count();   #  收益信息
                $item['user_num'] = Db::name('user')->where('agency_id', $item['id'])->count();  # 代理用户
                $item['goods_num'] = Db::name('agency_goods')->where('agency_id', $item['id'])->count();   # 商品管理
                return $item;
            });
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }


    /**
     * 获取单条信息
     * @param $id
     * @return array
     */
    public function getInfoOne($id)
    {
        $data = $this
            ->alias("a")
            ->join("t_user b", "a.user_id=b.id")
            ->where("a.id", $id)
            ->field("a.*,b.nick_name")
            ->find();
        return $data;
    }

    /**
     * 获取代理商信息
     * @param $user_id
     * @param $field
     * @return array
     */
    public static function getAgencyInfo($user_id, $field = "a.id,a.agency_name,a.user_id,a.agency_img,a.agency_price,a.status,a.agency_province,a.agency_city,a.agency_detail_address,a.status,b.nick_name")
    {
        $data = self::alias("a")->join("t_user b", "a.user_id=b.id")->where("a.user_id", $user_id)
            ->field($field)
            ->find();
        return $data;
    }

    /**
     * 获取最近的代理商
     * @param $lat
     * @param $lng
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRimAgency($lat, $lng)
    {
        $data = $this->field("id,agency_range,agency_title,abs($lng-agency_lng)+abs($lat-agency_lat) as distance,agency_lng,agency_lat")->order('distance asc')->limit(1)->find();
        $km = Util::getDistance($lng, $lat, $data['agency_lng'], $data['agency_lat']);//单位千米
        $distance = $data['agency_range'];
        if ($km > $distance) {
            return [];
        }
        return $data;
    }

    /**
     * 改变代理商收益情况
     * @param $agency_id
     * @param $price
     * @param int $type
     * @param string $change
     * @param string $order_sn
     * @param string $pay_sn
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeEarnings($agency_id, $price, $type = 1, $change = 'add', $order_sn = '', $pay_sn = '')
    {
        $map = [
            'id' => $agency_id
        ];
        $agency_data = $this->where($map)->field('agency_price')->find();
        if (empty($agency_data)) {
            $return_data['code'] = 0;
            $return_data['msg'] = "代理商数据不存在";
            return $return_data;
        }
        $last_price = $agency_data['agency_price'];
        $detail = "";
        switch (intval($type)) {
            // 1代理商佣金2商品利润 3代理商提现
            case 1:
                $detail = "佣金 ";
                break;
            case 2:
                $detail = "利润 ";
                break;
            case 3:
                $detail = "提现 ";
                break;
        }
        $check = 0;
        switch ($change) {
            case 'add':
                $up_data = [
                    'agency_price' => floatval($agency_data['agency_price']) + floatval($price)
                ];
                $detail .= "获得收益";
                $check = 0;
                break;
            case 'pay':
                $pay_price = floatval($agency_data['agency_price']) - floatval($price);
                if ($pay_price < 0) {
                    $return_data['code'] = 0;
                    $return_data['msg'] = "收益余额不足";
                    return $return_data;
                }
                $up_data = [
                    'agency_price' => $pay_price
                ];
                $detail .= "减少收益";
                $check = 0;
                break;
            case 'extract':
                $pay_price = floatval($agency_data['agency_price']) - floatval($price);
                if ($pay_price < 0) {
                    $return_data['code'] = 0;
                    $return_data['msg'] = "收益余额不足";
                    return $return_data;
                }
                $up_data = [
                    'agency_price' => $pay_price
                ];
                $detail .= "减少收益";
                $check = 1;
                break;
            default:
                $return_data['code'] = 0;
                $return_data['msg'] = "参数有误";
                return $return_data;
        }
        $ret = $this->where($map)->update($up_data);
        if ($ret !== false) {
            $earnings = [
                'agency_id' => $agency_id,
                'pay_sn' => $pay_sn,
                'order_sn' => $order_sn,
                'type' => $type,
                'price' => $price,
                'last_price' => $last_price,
                'change' => $change,
                'detail' => $detail,
                'check' => $check
            ];
            $agency_earnings_model = new AgencyEarningsModel();
            $ret = $agency_earnings_model->addEarnings($earnings);
            if (!empty($ret)) {
                $return_data['code'] = 1;
                $return_data['id'] = $ret;
                $return_data['msg'] = "操作成功";
                return $return_data;
            }
        }
        $return_data['code'] = 0;
        $return_data['msg'] = "操作失败";
        return $return_data;
    }
}
